package by.parfen.game.servlet.filters;

import java.io.IOException;
import java.util.Date;
import java.util.logging.Logger;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import by.parfen.game.datamodel.SessionObject;
import by.parfen.game.datamodel.SessionsData;

@WebFilter(filterName = "SessionFilter", urlPatterns = { "/*" })
public class SessionFilter implements Filter {

	private static final Logger LOGGER = Logger.getLogger(SessionFilter.class.getName());

	private SessionsData sessionData;

	@Override
	public void destroy() {
		// TODO Auto-generated method stub

	}

	@Override
	public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
			throws IOException, ServletException {
		HttpServletRequest request = (HttpServletRequest) req;
		HttpSession httpSession = ((HttpServletRequest) req).getSession();

		String sessionId = httpSession.getId();

		// as example of storing some session data (session id)
		sessionData.addSessionId(sessionId);
		LOGGER.info("List of sessions:");
		for (SessionObject sessionObject : sessionData.sessionDataList()) {
			LOGGER.info(sessionObject.getSessionId());
		}

		// Log the IP address and current timestamp.
		LOGGER.info("Session: " + sessionId + ", Time " + new Date().toString());

		// List<String> users = (List<String>)
		// request.getSession().getAttribute("users");
		// for (int i = 0; null != users && i < users.size(); i++) {
		// if (i == 0) {
		// LOGGER.info("Sessions users list");
		// }
		// LOGGER.info(users.get(i));
		// }
		// String lastUser = (String)
		// request.getSession().getAttribute("lastUser");
		// if (lastUser != null) {
		// LOGGER.info("Last user: " + lastUser);
		// }
		System.out.println(String.format("%s %s", "req.getAttrib: ", httpSession.getAttribute("countOfSession")));

		chain.doFilter(req, res);
	}

	@Override
	public void init(FilterConfig config) throws ServletException {
		// Get init parameter
		String testParam = config.getInitParameter("test-param");

		// Print the init parameter
		LOGGER.info("Test Param: " + testParam);

		sessionData = new SessionsData();

	}

}
